<?
//ob
ob_start();

//configuration
include "../conf.php";

//includes
include "../php/functions.php";

include "../php/facebook.api.php";
include "../php/auth.facebook.php";


//connect2db
$_DB = new PDO("mysql:host={$_MYSQL['host']};dbname={$_MYSQL['db_name']}", $_MYSQL['db_user'], $_MYSQL['password']);

while($task=$_DB->query("SELECT * FROM `cronjobs` WHERE `reserved`=0 AND `time` < ".time()." ORDER BY `time` ASC LIMIT 1")->fetch()) {
	try {
		$_DB->query("UPDATE `cronjobs` SET `reserved`=1 WHERE `id`=".$task['id']);
		$task_data=json_decode($task['data'],true);
		switch($task['type']) {
			case "wallstream":
				//~ print_r($task_data);
				$userInfo=get_userInfo($task_data['email']);
				$message=$task_data['message'];
				$attachment = array(
					'name' =>$task_data['name'],
					'link' =>$task_data['link'],
					'description' =>$task_data['description'],
					'picture' =>$task_data['picture']
					);
				$action_links = array( array('name' => 'balladsnbullets', 'link' => 'http://apps.facebook.com/balladsnbullets/'));
				//~ echo "pic--",$task_data['picture'],"--";
				$_FB = new Facebook($_FACEBOOK);
				$_FB->setAccessToken($userInfo['authtoken']);
				//~ echo $_FB->getAccessToken();
				publish_to_wall($message,$attachment,$action_links,$userInfo['fbid']);
				break;
			case "crmmail":
				//$userInfo=get_userInfo($task_data['email']);
				$message=$task_data['message'];
				$subject = $task_data['subject'];
				mail($task_data['email'], $subject, $message,"MIME-Version: 1.0\r\nContent-type: text/html; charset=utf-8\r\nFrom: legends@inlegend.de\r\nReply-To: legends@inlegend.de\r\n");
				$_DB->prepare("UPDATE `user` SET `crm`=1 , WHERE `email`= :email")->execute(array('email'=>$task_data['email'])); 
				break;
		}
	$_DB->query("DELETE FROM `cronjobs` WHERE `id`=".$task['id']);
	echo "did task {$task['id']} for user {$userInfo['fbid']} with email {$task_data['email']}...\n";
	}
	catch(Exception $error) {
		$emm= $error->getMessage()."";
		$_DB->prepare("UPDATE `cronjobs` SET `error`=1 , `errormessage` = :em WHERE `id`= :id")->execute(array('em'=>$emm,'id'=>$task['id']));
		echo "error in task {$task['id']} for user {$userInfo['fbid']}...\n";
	}
	flush();
}
?>